# lib/stair_master/workflow_map/step.rb

## StairMaster::WorkerflowMap::Step
##
## Represents a specific step in your workflow map
##
module StairMaster
  module WorkflowMap
    class Step
      ## Attributes/Fields --------------------------------
      attr_reader   :key,
                    :controller,
                    :label,
                    :route_to,
                    :map

      ## Initializer --------------------------------------
      def initialize(key, label, options={})
        @key        = key.to_sym
        @controller = options.fetch :controller, key
        @label      = label
        @path       = options.fetch :route_to, nil
        @map        = options.fetch :map, nil
      end

      ## Methods ------------------------------------------

      def rules
        @map.workflow_rules[@key]
      end

      def test_rules(context)
        if rules.empty?
          return false
        else
          return rules.each{ |rule| rule.pass?(context) }.all?
        end
      end

      ## Test whether this step should be skipped or not
      ##
      def skip?(context)
        # rules = @conditions[:skippable]
        # ( rules.empty? ? [false] : test_rules(rules, context) ).all?
        Rails.logger.debug "="*80
        Rails.logger.debug "SKIP?"
        Rails.logger.debug test_rules(context)
        Rails.logger.debug "="*80
        # test_rules(context)
        false
      end

      ## Using the path, we want to return the rendered
      ## URL that should be used to access this step
      ##
      def url_for(resources=[], options={})
        begin
          ## TODO: There is probably a better way to handle this.
          resources = resources.nil? ? [] : resources
          router.send @path.to_sym, (resources.empty? ? nil : resources), options
        rescue Exception => e
          raise RuntimeError, "Could not find the route '#{ @path }' in your application. #{ e.message }"
        end
      end

      def to_s
        self.label
      end

      private # -------------------------------------------

      def router
        @router ||= Rails.application.routes.url_helpers
      end
    end
  end
end
